//
//  HZL_NetworkingHandle.m
//  B_Project
//
//  Created by 胡佳俊 on 15/11/24.
//  Copyright © 2015年 HZL. All rights reserved.
//

#import "HZL_NetworkingHandle.h"
#import "AFNetworking.h"
@implementation HZL_NetworkingHandle
#pragma mark - GET请求
// GET 请求
+ (void)getUrl:(NSString *)url cookie:(NSString *)cookie result:(JSONBLOCK)block
{
    //    NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    if (cookie) {
        // 接口带Cookie
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 返回数据的格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        // 如果请求成功 回调 请求到的数据 同时在这里 做本地缓存
        // 本地缓存
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//        NSLog(@"%@", path_doc);
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        id respose = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        block(respose);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // 在这里读取本地缓存
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
//        NSLog(@"!!!!!%@", path_doc);
        if (result) {
            id dic = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
            block(dic);
        }
        else {
            
            block(nil);
        }
        
        NSLog(@"网络请求错误原因: %@", error);
    }];
    
}
// POST 请求
+ (void)postUrl:(NSString *)url parame:(id)parame cookie:(NSString *)cookie result:(JSONBLOCK)block
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    if (cookie) {
        // 接口带Cookie
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    // 返回数据的格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    
    [manager POST:url parameters:parame success:^(NSURLSessionDataTask *task, id responseObject) {
        // 如果请求成功 回调 请求到的数据 同时在这里 做本地缓存
        // 本地缓存
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        block(responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // 在这里读取本地缓存
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        
        block(result);
        
        NSLog(@"网络请求错误原因: %@", error);
        
    }];
    
}
#pragma mark - POST请求
+ (void)requestPOSTWithURl:(NSString *)urlStr body:(NSString *)body completion:(JSONBLOCK)block
{
    /****** 异步POST网络请求 *****/
    NSString *newStr  = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:newStr];
    // POST请求必须使用可变
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    // 请求类型设置
    request.HTTPMethod = @"POST";
    // body设置
    NSData * bodata = [body dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = bodata;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"网络请求错误: %@", connectionError);
            exit(0);
        }
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"解析错误 :%@", error);
//            exit(0);
        }
        block(result);
    }];
}
#pragma mark - 网络请求状态判断
+ (void)networkReachabilityStatus:(JSONBLOCK)block
{
    // 网络连接检测封装
    AFNetworkReachabilityManager *reachManeger = [AFNetworkReachabilityManager sharedManager];
    // 开始检测
    [reachManeger startMonitoring];
    
    [reachManeger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                block(@0);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                block(@1);
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                block(@2);
                break;
            case AFNetworkReachabilityStatusUnknown:
                block(@(-1));
                break;
            default:
                break;
        }
    }];
    
}

// 音乐GET请求
+ (void)getUrl:(NSString *)url musicCookie:(NSString *)cookie result:(JSONBLOCK)block
{
    NSString *urlStr = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    if (cookie) {
        // 接口带Cookie
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"X-Im-Id"];
    }
    //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 返回数据的格式
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    
    [manager GET:urlStr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        // 如果请求成功 回调 请求到的数据 同时在这里 做本地缓存
        // 本地缓存
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        //        NSLog(@"%@", path_doc);
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        id respose = responseObject;
        block(respose);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // 在这里读取本地缓存
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [url hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        NSLog(@"!!!!!%@", path_doc);
        if (result) {
            id dic = result;
            block(dic);
        }
        else {
            
            block(nil);
        }
        
        NSLog(@"网络请求错误原因: %@", error);
    }];
    
}


@end
